package com.cwf.auth.service.impl;

import com.cwf.auth.data.ContextMap;
import com.cwf.auth.dto.LoginDTO;
import com.cwf.auth.service.ILoginService;
import com.cwf.auth.vo.LoginVO;
import com.cwf.org.domain.Employee;
import com.cwf.org.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

@Service
public class ILoginServiceImpl implements ILoginService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public LoginVO login(LoginDTO loginDTO) {
        // 校验密码是否为空
        if (Objects.isNull(loginDTO.getUsername()) || Objects.isNull(loginDTO.getPassword()))
            throw new RuntimeException("账号密码为空");
        /*
        方案一：账号密码一起查 直接返回对象通过是否为空 判断是否登录成功
        方案二：根据账号查询对象
                在判断对象密码是否匹配
                最后返回结果
         */
        Employee employee = employeeMapper.queryByUsername(loginDTO);
        if (Objects.isNull(employee))
            throw new RuntimeException("账号密码错误");
        if (!employee.getPassword().equals(loginDTO.getPassword().trim()))
            throw new RuntimeException("密码错误");
        LoginVO loginVO = new LoginVO();
        // 数据脱敏
        Employee user = new Employee();
        user.setUsername(employee.getUsername());
        user.setAge(employee.getAge());
        String token = UUID.randomUUID().toString();
        loginVO.setToken(token);
        loginVO.setUser(user);
        // 存全局map,如果使用employee脱敏，那么你存的map终究没有id了
        ContextMap.loginMap.put(token,employee);
        return loginVO;
    }
}
